package com.my.assembly.handler.utils;

import android.util.Base64;
import android.util.Log;

import com.laojiang.imagepickers.data.MediaDataBean;
import com.my.assembly.config.Config;
import com.my.assembly.http.HttpClient;

import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * <pre>
 *     author : wuxiaoqi
 *     e-mail : 1321972760@qq.com
 *     time   : 2018/12/02
 *     desc   : 上传文件工具
 *     version: 1.0
 * </pre>
 */
public class UploadFileUtil {

    private UploadCallback mCallback;

    public void upload(final ArrayList<MediaDataBean> fileData, final UploadCallback callback) {
        if (fileData == null || fileData.size() == 0) {
            return;
        }
        this.mCallback = callback;
        if (fileData.size() == 1 && fileData.get(0).getType() == 1) {
            uploadVideo(fileData.get(0).getMediaPath());
        } else {
            uploadPic(fileData);
        }
    }

    /**
     * 上传视频
     */
    private void uploadVideo(String path) {
        File file = new File(path);
        RequestParams params = new RequestParams(Config.base_url + "/WebApp/PhotoBooks/AppUploadMv");
        params.setAsJsonContent(true);
        List<KeyValue> list = new ArrayList<>();
        list.add(new KeyValue("file", file));
        String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(file.lastModified()));
        org.xutils.http.body.MultipartBody body = new org.xutils.http.body.MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        params.addHeader("DEVICEINFO", "JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU");
        params.addBodyParameter("timestamp", ctime);
        x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mCallback.success(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("wxq", "上传视频失败" + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void uploadSyncFile(File file) {
        try {
            String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(file.lastModified()));
            MultipartBody.Builder builder = new MultipartBody.Builder();
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
            builder.setType(MultipartBody.FORM);
            builder.addFormDataPart("timestamp", ctime);
            builder.addFormDataPart("file", file.getName(), requestBody);
            MultipartBody multipartBody = builder.build();
            Response execute = HttpClient.getInstance().getClient()
                    .newCall(new Request.Builder().url(Config.base_url + "/AppUpload.php")
                            .addHeader("DEVICEINFO", "JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU")
                            .method("POST", multipartBody).build()).execute();
            if (execute.isSuccessful()) {
                final String result = execute.body().string();
                mCallback.success(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传图片
     */
    private void uploadPic(final ArrayList<MediaDataBean> fileData) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < fileData.size(); i++) {
                    try {
                        File file = new File(fileData.get(i).getMediaPath());
//                        String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(file.lastModified()));
//                        String s = encodeImage(new File(fileData.get(i).getMediaPath()));
//                        RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "imgData=" + s + "&timestamp=" + ctime);
//                        Response execute = HttpClient.getInstance().getClient()
//                                .newCall(new Request.Builder().url(Config.base_url + "/AppUpload.php")
//                                        .addHeader("DEVICEINFO", "JxRaZezavm3HXM3d9pWnYiqqQC1SJbsU")
//                                        .method("POST", body).build()).execute();
//                        if (execute.isSuccessful()) {
//                            final String result = execute.body().string();
//                        }
                        uploadSyncFile(file);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
